package com.sonicvision.resourcetracker.mailmerge;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelReader {

	public List<Contact> getContactsFromExcel(InputStream inputStream)
			throws IOException {

		List<Contact> contacts = new ArrayList<Contact>();

		// Get first sheet from the workbook
		XSSFSheet sheet = new XSSFWorkbook(inputStream).getSheet("MailMerge");

		// Iterate through each rows from first sheet
		Iterator<Row> rowIterator = sheet.iterator();
		while (rowIterator.hasNext()) {
			Row row = rowIterator.next();

			// ignore the first row since it is a header row
			if (row.getRowNum() == 0) {
				continue;
			}

			String firstName = "";
			String lastName = "";
			String email = "";

			// For each row, iterate through each columns
			Iterator<Cell> cellIterator = row.cellIterator();
			while (cellIterator.hasNext()) {

				Cell cell = cellIterator.next();

				String cellValue = cell.getStringCellValue();

				if (cell.getColumnIndex() == 0) {
					firstName = cellValue;
				} else if (cell.getColumnIndex() == 1) {
					email = cellValue;
				}
			}

			Contact contact = new Contact(firstName, lastName, email);
			contacts.add(contact);
		}

		return contacts;
	}
}
